package com.zshan.clinic.admin.service.stock;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.stock.SpecStockSupplyMapper;
import com.zshan.clinic.admin.service.clinic.ClinicEmpService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.enums.YesOrNoEnum;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.common.util.validate.PhoneValidator;
import com.zshan.clinic.database.dao.StockMfrMapper;
import com.zshan.clinic.database.dao.StockStorageMapper;
import com.zshan.clinic.database.dao.StockSupplyMapper;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 药品库房
 */
@Slf4j
@Service
public class StockSupplyService {

    @Autowired
    private StockStorageMapper stockStorageMapper;

    @Autowired
    private StockMfrMapper stockMfrMapper;

    @Autowired
    private StockSupplyMapper stockSupplyMapper;

    @Autowired
    private SpecStockSupplyMapper specStockSupplyMapper;

    @Autowired
    private StockDrugService stockDrugService;

    @Autowired
    private ClinicEmpService clinicEmpService;


    /**
     * 查询厂家下拉框
     * @param clinicId
     * @return
     */
    public List<StockMfrSelectVo> getMfrSelectList(Long clinicId) {
        List<StockMfr> mfrList = getMfrListByClinicId(clinicId);
        if(CollectionUtils.isEmpty(mfrList)){
            return null;
        }
        return mfrList.stream().map(stockMfr -> {
            StockMfrSelectVo vo = new StockMfrSelectVo();
            BeanUtils.copyProperties(stockMfr, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 根据诊所查询厂家数据
     * @param clinicId
     * @return
     */
    public List<StockMfr> getMfrListByClinicId(Long clinicId) {
        StockMfrExample example = new StockMfrExample();
        StockMfrExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockMfrMapper.selectByExample(example);
    }

    /**
     * 查询药库下拉框列表
     * @param clinicId
     * @return
     */
    public List<StockStorageSelectVo> getStorageSelectList(Long clinicId) {
        List<StockStorage> stockStorageList = getStorageListByClinicId(clinicId);
        if(CollectionUtils.isEmpty(stockStorageList)){
            return null;
        }
        return stockStorageList.stream().map(stockStorage -> {
                    StockStorageSelectVo vo = new StockStorageSelectVo();
                    BeanUtils.copyProperties(stockStorage, vo);
                    return vo;
                }).collect(Collectors.toList());
    }

    /**
     * 查询供应商下拉框列表
     * @param clinicId
     * @return
     */
    public List<StockSupplySelectVo> getSupplySelectList(Long clinicId) {
        List<StockSupply> supplyList = getSupplyListByClinicId(clinicId);
        if(CollectionUtils.isEmpty(supplyList)){
            return null;
        }
        return supplyList.stream().map(stockSupply -> {
            StockSupplySelectVo vo = new StockSupplySelectVo();
            BeanUtils.copyProperties(stockSupply, vo);
            return vo;
        }).collect(Collectors.toList());
    }


    public List<StockSupply> getSupplyListByClinicId(Long clinicId) {
        StockSupplyExample example = new StockSupplyExample();
        StockSupplyExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockSupplyMapper.selectByExample(example);
    }

    /**
     * 查询默认药库
     * @param clinicId
     * @return
     */
    public List<StockStorage> getStorageListByClinicId(Long clinicId){
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOrderByClause("is_default desc");
        return stockStorageMapper.selectByExample(example);
    }

    /**
     * 查询诊所供应商列表
     * @param clinicId
     * @param clinicId
     * @return
     */
    public PageInfo<StockSupplyVo> getSupplyList(Long clinicId, String supplyName, Integer pageNo, Integer pageSize){
        Long totalCount = specStockSupplyMapper.getSupplyCount(clinicId,supplyName);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockSupplyVo> supplyList = specStockSupplyMapper.getSupplyList(clinicId,supplyName,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,supplyList);
    }

    /**
     * 查询诊所药库列表
     * @param clinicId
     * @param clinicId
     * @return
     */
    public PageInfo<StockStorageVo> getStorageList(Long clinicId, String storageName, Integer pageNo, Integer pageSize){
        Long totalCount = specStockSupplyMapper.getStorageCount(clinicId,storageName);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<StockStorageVo> stockStorageList = specStockSupplyMapper.getStorageList(clinicId,storageName,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,stockStorageList);
    }



    public Long getStockStorageCountByParams(Long clinicId, String storageName) {
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotBlank(storageName)){
            criteria.andStorageNameLike("%"+storageName+"%");
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockStorageMapper.countByExample(example);
    }

    public List<StockStorage> getStockStorageListByParams(Long clinicId,String storageName,Integer pageNo, Integer pageSize){
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotBlank(storageName)){
            criteria.andStorageNameLike("%"+storageName+"%");
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo,pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        return stockStorageMapper.selectByExample(example);
    }

    /**
     * 查询厂家列表
     * @param clinicId
     * @param clinicId
     * @return
     */
    public PageInfo<StockMfrVo> getMfrList(Long clinicId, String mfrName, Integer pageNo, Integer pageSize){
        if(StringUtil.isBlank(clinicId)){
            return PageInfo.build();
        }
        Long totalCount = getStockMfrCountByParams(clinicId,mfrName);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();

        }
        List<StockMfr> stockMfrList = getStockMfrListByParams(clinicId,mfrName,pageNo,pageSize);
        // 将实体列表转换为DTO列表
        return new PageInfo<>(totalCount,stockMfrList.stream().map(stockMfr -> {
            StockMfrVo stockMfrVo = new StockMfrVo();
            BeanUtils.copyProperties(stockMfr, stockMfrVo);
            return stockMfrVo;
        }).collect(Collectors.toList()));
    }


    public Long getStockMfrCountByParams(Long clinicId,String mfrName){
        StockMfrExample example = new StockMfrExample();
        StockMfrExample.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotBlank(mfrName)){
            criteria.andMfrNameLike("%"+mfrName+"%");
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockMfrMapper.countByExample(example);
    }


    public List<StockMfr> getStockMfrListByParams(Long clinicId,String mfrName,Integer pageNo, Integer pageSize){
        StockMfrExample example = new StockMfrExample();
        StockMfrExample.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotBlank(mfrName)){
            criteria.andMfrNameLike("%"+mfrName+"%");
        }
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo,pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        return stockMfrMapper.selectByExample(example);
    }


    public List<StockSupply> getStockSupplyListByParams(Long clinicId, String supplyName, Integer pageNo, Integer pageSize) {
        StockSupplyExample example = new StockSupplyExample();
        StockSupplyExample.Criteria criteria = example.createCriteria();
        if (clinicId != null) {
            criteria.andClinicIdEqualTo(clinicId);
        }
        if (StringUtil.isNotBlank(supplyName)) {
            criteria.andSupplyNameLike("%" + supplyName + "%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        return stockSupplyMapper.selectByExample(example);
    }

    /**
     * 添加供应商
     * @param stockSupply
     */
    @Transactional(rollbackFor = Exception.class)
    public void addSupply(StockSupply stockSupply) {
        validateStockSupply(stockSupply);
        stockSupply.setIsDelete(YesOrNoEnum.NO.getValue());
        stockSupply.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockSupply.setCreateTime(new Date());
        stockSupplyMapper.insertSelective(stockSupply);
    }

    /**
     * 根据名称查询供应商数量
     * @param supplyId
     * @return
     */
    public Long getStockSupplyByName(String supplyName,Long supplyId){
        StockSupplyExample example = new StockSupplyExample();
        StockSupplyExample.Criteria criteria = example.createCriteria();
        criteria.andSupplyNameEqualTo(supplyName);
        if(!StringUtil.isBlank(supplyId)){
            criteria.andSupplyIdNotEqualTo(supplyId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return stockSupplyMapper.countByExample(example);
    }

    public void validateStockSupply(StockSupply stockSupply) {
        stockSupply.setSupplyName(StringUtil.removeAllWhitespace(stockSupply.getSupplyName()));
        if (StringUtil.isBlank(stockSupply.getSupplyName())) {
            throw new BusinessFailException("供应商名称不能为空");
        }
        if(stockSupply.getSupplyName().length() > Constants.SUPPLY_NAME_LENGTH){
            throw new BusinessFailException("供应商名称"+ Constants.SUPPLY_NAME_LENGTH+"字以内！");
        }
        stockSupply.setManagerName(StringUtil.removeAllWhitespace(stockSupply.getManagerName()));
        if (StringUtil.isBlank(stockSupply.getManagerName())) {
            throw new BusinessFailException("联系人不能为空");
        }
        if(stockSupply.getManagerName().length() > Constants.SUPPLY_MANAGER_NAME_LENGTH){
            throw new BusinessFailException("联系人"+ Constants.SUPPLY_MANAGER_NAME_LENGTH+"字以内！");
        }
        if (StringUtil.isBlank(stockSupply.getManagerPhone())) {
            throw new BusinessFailException("联系电话不能为空");
        }
        if(!PhoneValidator.isValidMobile(stockSupply.getManagerPhone()) && !PhoneValidator.isValidLandline(stockSupply.getManagerPhone())){
            throw new BusinessFailException("手机号格式错误！");
        }
        Long clinicCount = getStockSupplyByName(stockSupply.getSupplyName(),stockSupply.getSupplyId());
        if(clinicCount > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("供应商名称不能重复！");
        }
    }

    public StockSupply getEnableSupplyById(Long supplyId) {
        StockSupply stockSupply = getSupplyById(supplyId);
        if(stockSupply == null){
            return null;
        }
        if(YesOrNoEnum.NO.getValue().equals(stockSupply.getIsEnabled())){
            return null;
        }
        return stockSupply;
    }

    /**
     * 获取供应商
     * @param supplyId
     * @return
     */
    public StockSupply getSupplyById(Long supplyId) {
        if (supplyId == null) {
            return null;
        }
        StockSupply stockSupply = stockSupplyMapper.selectByPrimaryKey(supplyId);
        if (stockSupply == null || YesOrNoEnum.YES.getValue().equals(stockSupply.getIsDelete())) {
            return null;
        }
        return stockSupply;
    }

    /**
     * 修改供应商
     * @param stockSupply
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSupply(StockSupply stockSupply) {
        validateStockSupply(stockSupply);
        StockSupply dbStockSupply = getSupplyById(stockSupply.getSupplyId());
        if (dbStockSupply == null) {
            throw new BusinessFailException("供应商不存在");
        }
        stockSupply.setUpdateTime(new Date());
        stockSupplyMapper.updateByPrimaryKeySelective(stockSupply);
    }

    /**
     * 删除供应商
     * @param stockSupply
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteSupply(StockSupply stockSupply) {
        StockSupply dbStockSupply = getSupplyById(stockSupply.getSupplyId());
        if (dbStockSupply == null) {
            throw new BusinessFailException("供应商不存在");
        }
        dbStockSupply.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockSupply.setUpdateUserId(stockSupply.getUpdateUserId());
        dbStockSupply.setUpdateBy(stockSupply.getUpdateBy());
        dbStockSupply.setUpdateTime(new Date());
        stockSupplyMapper.updateByPrimaryKeySelective(dbStockSupply);
    }

    /**
     * 启用供应商
     * @param stockSupply
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableSupply(StockSupply stockSupply) {
        StockSupply dbStockSupply = getSupplyById(stockSupply.getSupplyId());
        if (dbStockSupply == null) {
            throw new BusinessFailException("供应商不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbStockSupply.getIsEnabled())) {
            return;
        }
        dbStockSupply.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockSupply.setUpdateUserId(stockSupply.getUpdateUserId());
        dbStockSupply.setUpdateBy(stockSupply.getUpdateBy());
        dbStockSupply.setUpdateTime(new Date());
        stockSupplyMapper.updateByPrimaryKeySelective(dbStockSupply);
    }

    /**
     * 停用供应商
     * @param stockSupply
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableSupply(StockSupply stockSupply) {
        StockSupply dbStockSupply = getSupplyById(stockSupply.getSupplyId());
        if (dbStockSupply == null) {
            throw new BusinessFailException("供应商不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbStockSupply.getIsEnabled())) {
            return;
        }
        dbStockSupply.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockSupply.setUpdateUserId(stockSupply.getUpdateUserId());
        dbStockSupply.setUpdateBy(stockSupply.getUpdateBy());
        dbStockSupply.setUpdateTime(new Date());
        stockSupplyMapper.updateByPrimaryKeySelective(dbStockSupply);
    }

    /**
     * 添加厂家
     * @param stockMfr
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMfr(StockMfr stockMfr) {
        validateStockMfr(stockMfr);
        stockMfr.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockMfr.setIsDelete(YesOrNoEnum.NO.getValue());
        stockMfr.setCreateTime(new Date());
        stockMfrMapper.insertSelective(stockMfr);
    }


    public void validateStockMfr(StockMfr stockMfr) {
        stockMfr.setMfrName(StringUtil.removeAllWhitespace(stockMfr.getMfrName()));
        if(StringUtil.isBlank(stockMfr.getMfrName())){
            throw new BusinessFailException("厂家名称不能为空");
        }
        if(stockMfr.getMfrName().length() > Constants.MFR_LENGTH){
            throw new BusinessFailException("厂家名称"+Constants.MFR_LENGTH+"个字以内！");
        }
        Long mfrCount = getMfrCountByName(stockMfr.getClinicId(),stockMfr.getMfrId(),stockMfr.getMfrName());
        if(mfrCount > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("厂家名称重复！");
        }
    }

    /**
     * 根据名字查询
     * @param clinicId
     * @param mfrId
     * @param mfrName
     * @return
     */
    public Long getMfrCountByName(Long clinicId, Long mfrId, String mfrName) {
        StockMfrExample example = new StockMfrExample();
        StockMfrExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andMfrNameEqualTo(mfrName);
        if(!StringUtil.isBlank(mfrId)){
            criteria.andMfrIdNotEqualTo(mfrId);
        }
        return stockMfrMapper.countByExample(example);
    }

    /**
     * 根据ID查询药品厂家
     * @param mfrId
     * @return
     */
    public StockMfr getStockMfrById(Long mfrId){
        if(StringUtil.isBlank(mfrId)){
            return null;
        }
        StockMfr stockMfr = stockMfrMapper.selectByPrimaryKey(mfrId);
        if(stockMfr == null || YesOrNoEnum.YES.getValue().equals(stockMfr.getIsDelete())){
            return null;
        }
        return stockMfr;
    }


    /**
     * 修改厂家
     * @param stockMfr
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMfr(StockMfr stockMfr) {
        validateStockMfr(stockMfr);
        StockMfr dbStockMfr = getStockMfrById(stockMfr.getMfrId());
        if(dbStockMfr == null){
            throw new BusinessFailException("厂家不存在");
        }
        stockMfr.setUpdateTime(new Date());
        stockMfrMapper.updateByPrimaryKeySelective(stockMfr);
    }


    /**
     * 删除厂家
     * @param stockMfr
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMfr(StockMfr stockMfr) {
        StockMfr dbStockMfr = getStockMfrById(stockMfr.getMfrId());
        if(dbStockMfr == null){
            throw new BusinessFailException("厂家不存在");
        }
        dbStockMfr.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockMfr.setUpdateUserId(stockMfr.getUpdateUserId());
        dbStockMfr.setUpdateBy(stockMfr.getUpdateBy());
        dbStockMfr.setUpdateTime(new Date());
        stockMfrMapper.updateByPrimaryKeySelective(dbStockMfr);
    }

    /**
     * 启用厂家
     * @param stockMfr
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableMfr(StockMfr stockMfr) {
        StockMfr dbStockMfr = getStockMfrById(stockMfr.getMfrId());
        if(dbStockMfr == null){
            throw new BusinessFailException("厂家不存在");
        }
        if(YesOrNoEnum.YES.getValue().equals(dbStockMfr.getIsEnabled())){
            return;
        }
        dbStockMfr.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockMfr.setUpdateUserId(stockMfr.getUpdateUserId());
        dbStockMfr.setUpdateBy(stockMfr.getUpdateBy());
        dbStockMfr.setUpdateTime(new Date());
        stockMfrMapper.updateByPrimaryKeySelective(dbStockMfr);
    }

    /**
     * 停用厂家
     * @param stockMfr
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableMfr(StockMfr stockMfr) {
        StockMfr dbStockMfr = getStockMfrById(stockMfr.getMfrId());
        if(dbStockMfr == null){
            throw new BusinessFailException("厂家不存在");
        }
        if(YesOrNoEnum.NO.getValue().equals(dbStockMfr.getIsEnabled())){
            return;
        }
        dbStockMfr.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockMfr.setUpdateUserId(stockMfr.getUpdateUserId());
        dbStockMfr.setUpdateBy(stockMfr.getUpdateBy());
        dbStockMfr.setUpdateTime(new Date());
        stockMfrMapper.updateByPrimaryKeySelective(dbStockMfr);
    }


    /**
     * 添加药库
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void addStorage(StockStorage stockStorage) {
        validateStockStorage(stockStorage);
        Long defaultCount = getDefaultCount(stockStorage.getClinicId());
        if(defaultCount <= CommonConstant.DEFAULT_0){
            stockStorage.setIsDefault(YesOrNoEnum.YES.getValue());
        }else {
            stockStorage.setIsDefault(YesOrNoEnum.NO.getValue());
        }
        stockStorage.setIsDelete(YesOrNoEnum.NO.getValue());
        stockStorage.setIsEnabled(YesOrNoEnum.YES.getValue());
        stockStorage.setCreateTime(new Date());
        stockStorageMapper.insertSelective(stockStorage);
    }

    /**
     * 获取默认的药库数量
     * @param clinicId
     * @return
     */
    public Long getDefaultCount(Long clinicId){
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDefaultEqualTo(YesOrNoEnum.YES.getValue());
        return stockStorageMapper.countByExample(example);
    }

    /**
     *
     * @param stockStorage
     */
    public void validateStockStorage(StockStorage stockStorage) {
        stockStorage.setStorageName(StringUtil.removeAllWhitespace(stockStorage.getStorageName()));
        if(StringUtil.isBlank(stockStorage.getStorageName())){
            throw new BusinessFailException("药库名称不能为空");
        }
        if(stockStorage.getStorageName().length() > Constants.STORAGE_LENGTH){
            throw new BusinessFailException("药库名称"+Constants.STORAGE_LENGTH+"个字以内！");
        }
        Long storageCount = getStorageCountByName(stockStorage.getClinicId(),stockStorage.getStorageId(),stockStorage.getStorageName());
        if(storageCount > CommonConstant.DEFAULT_0){
            throw new BusinessFailException("药库名称重复！");
        }
        ClinicEmp clinicEmp = clinicEmpService.getEnabledEmpById(stockStorage.getManagerId());
        if(clinicEmp == null || !clinicEmp.getClinicId().equals(stockStorage.getClinicId())){
            throw new BusinessFailException("员工不存在");
        }
    }

    public Long getStorageCountByName(Long clinicId,Long storageId,String storageName){
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andStorageNameEqualTo(storageName);
        if(!StringUtil.isBlank(storageId)){
            criteria.andStorageIdNotEqualTo(storageId);
        }
        return stockStorageMapper.countByExample(example);
    }


    /**
     * 根据ID查询诊所药库
     * @param storageId
     * @return
     */
    public StockStorage getStockStorageById(Long storageId){
        if(StringUtil.isBlank(storageId)){
            return null;
        }
        StockStorage stockStorage = stockStorageMapper.selectByPrimaryKey(storageId);
        if(stockStorage == null || YesOrNoEnum.YES.getValue().equals(stockStorage.getIsDelete())){
            return null;
        }
        return stockStorage;
    }

    public StockStorage getEnableStockStorageById(Long storageId){
        StockStorage stockStorage = getStockStorageById(storageId);
        if(stockStorage == null){
            return null;
        }
        if(YesOrNoEnum.NO.getValue().equals(stockStorage.getIsEnabled())){
            return null;
        }
        return stockStorage;
    }

    /**
     * 设置默认
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(StockStorage stockStorage) {
        StockStorage dbStockStorage = getStockStorageById(stockStorage.getStorageId());
        if(dbStockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        StockStorage defaultStockStorage = getDefaultStockStorage(stockStorage.getClinicId());
        if(defaultStockStorage != null){
            defaultStockStorage.setIsDefault(YesOrNoEnum.NO.getValue());
            defaultStockStorage.setUpdateUserId(stockStorage.getUpdateUserId());
            defaultStockStorage.setUpdateBy(stockStorage.getUpdateBy());
            defaultStockStorage.setUpdateTime(new Date());
            stockStorageMapper.updateByPrimaryKeySelective(defaultStockStorage);
        }
        dbStockStorage.setIsDefault(YesOrNoEnum.YES.getValue());
        dbStockStorage.setUpdateUserId(stockStorage.getUpdateUserId());
        dbStockStorage.setUpdateBy(stockStorage.getUpdateBy());
        dbStockStorage.setUpdateTime(new Date());
        stockStorageMapper.updateByPrimaryKeySelective(dbStockStorage);
    }

    public StockStorage getDefaultStockStorage(Long clinicId){
        StockStorageExample example = new StockStorageExample();
        StockStorageExample.Criteria criteria = example.createCriteria();
        criteria.andIsDefaultEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        example.setLimit(CommonConstant.DEFAULT_1);
        List<StockStorage> stockStorageList = stockStorageMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(stockStorageList)){
            return null;
        }
        return stockStorageList.get(0);
    }

    /**
     * 修改药库
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStorage(StockStorage stockStorage) {
        validateStockStorage(stockStorage);
        StockStorage dbStockStorage = getStockStorageById(stockStorage.getStorageId());
        if(dbStockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        stockStorage.setUpdateTime(new Date());
        stockStorageMapper.updateByPrimaryKeySelective(stockStorage);
    }



    /**
     * 删除药库
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteStorage(StockStorage stockStorage) {
        StockStorage dbStockStorage = getStockStorageById(stockStorage.getStorageId());
        if(dbStockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        //检查药库下是否存在库存
        if(stockDrugService.validateStockQty(stockStorage.getClinicId(),stockStorage.getStorageId())){
            throw new BusinessFailException("当前药库已产生库存，禁止删除！");
        }
        dbStockStorage.setIsDelete(YesOrNoEnum.YES.getValue());
        dbStockStorage.setUpdateUserId(stockStorage.getUpdateUserId());
        dbStockStorage.setUpdateBy(stockStorage.getUpdateBy());
        dbStockStorage.setUpdateTime(new Date());
        stockStorageMapper.updateByPrimaryKeySelective(dbStockStorage);
    }

    /**
     * 启用药库
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableStorage(StockStorage stockStorage) {
        StockStorage dbStockStorage = getStockStorageById(stockStorage.getStorageId());
        if(dbStockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        if(YesOrNoEnum.YES.getValue().equals(dbStockStorage.getIsEnabled())){
            return;
        }
        dbStockStorage.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbStockStorage.setUpdateUserId(stockStorage.getUpdateUserId());
        dbStockStorage.setUpdateBy(stockStorage.getUpdateBy());
        dbStockStorage.setUpdateTime(new Date());
        stockStorageMapper.updateByPrimaryKeySelective(dbStockStorage);
    }

    /**
     * 停用药库
     * @param stockStorage
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableStorage(StockStorage stockStorage) {
        StockStorage dbStockStorage = getStockStorageById(stockStorage.getStorageId());
        if(dbStockStorage == null){
            throw new BusinessFailException("药库不存在");
        }
        if(YesOrNoEnum.NO.getValue().equals(dbStockStorage.getIsEnabled())){
            return;
        }
        dbStockStorage.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbStockStorage.setUpdateUserId(stockStorage.getUpdateUserId());
        dbStockStorage.setUpdateBy(stockStorage.getUpdateBy());
        dbStockStorage.setUpdateTime(new Date());
        stockStorageMapper.updateByPrimaryKeySelective(dbStockStorage);
    }

}
